﻿using JhbyCommon.JhbyCommon.CommonMethods;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JhbyWebApi.ApiControllers
{
    public class FileterController : ActionFilterAttribute
    {
        private IHttpContextAccessor _accessor;
        public FileterController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //返回结果
            var result = new object();
            //session存值
            var httpContext = _accessor.HttpContext;
            SessionHelper session = new SessionHelper(httpContext);
            int userid = 0;
            int.TryParse(session.GetSession("Id"), out userid);

            var isDefined = false;
            var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
            if (controllerActionDescriptor != null)
            {
                isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                   .Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)));
            }
            if (isDefined) return;
            if (userid == 0)
            {
                result = new
                {
                    Code = 800,
                    message = "session值为空"
                };
                filterContext.Result = new JsonResult(result);
            }
            base.OnActionExecuting(filterContext);
        }
    }
    public class NoPermissionRequiredAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }

    }
}
